package com.aftersale.demo.service.impl;

import cn.hutool.core.util.StrUtil;
import com.aftersale.demo.entity.Result;
import com.aftersale.demo.entity.User;
import com.aftersale.demo.mapper.UserMapper;
import com.aftersale.demo.service.MailService;
import com.aftersale.demo.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;


import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.util.Objects;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author 空
 * @date 2023/10/28 20:02
 * @desc 发送验证码
 */
@Service
public class MailServiceImpl implements MailService {


    @Autowired
    RedisCache redisCache;

    @Autowired
    JavaMailSender javaMailSender;

    @Autowired
    ThreadServiceImpl threadService;

    @Autowired
    UserMapper userMapper;

    @Value("${spring.mail.username}")
    private String mailUserName;

    private String toEmail;
    private String param="用户名";
    @Override
    public Result getCode(String userName,String page,boolean existcode) {
        if(existcode){
            param="邮箱";
        }
        // 非空校验
        if (StrUtil.isBlank(userName)) {
            return Result.error("401",param+"不能为空");
        }
        // 账号存在校验
        if(!existcode){
            User user=userMapper.exits(new User(userName));
            if(Objects.isNull(user)){
                return Result.error("401","用户名不存在");
            }
            toEmail=user.getEmail();
        }else{
            toEmail=userName;
            if(!toEmail.matches("^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*\\.[a-zA-Z0-9]{2,6}$")){
                return Result.error("401","请输入正确的邮箱");
            }
        }


        //生成短信验证码
        String verifyCode = redisCache.getCacheObject(userName);
        if (verifyCode != null) {
            return Result.error("401","操作频繁，请稍后再试");

        }else{
            verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);
        }
        // 验证码存入redis并设置过期时间
        Integer overtime = 1; 
        
        redisCache.setCacheObject(userName, verifyCode, overtime, TimeUnit.MINUTES);

        // 编写邮箱内容
        StringBuilder text = new StringBuilder();
        text.append("<html><head><title></title></head><body>");
        text.append("亲爱的用户<br/>");
        text.append("您的验证码是：").append(verifyCode).append("<br/>");
        text.append("您可以复制此验证码并返回至售后服务系统"+page+"页面，以验证您的邮箱。<br/>");
        text.append("此验证码只能使用一次，在");
        text.append(overtime.toString());
        text.append("分钟内有效。验证成功则自动失效。<br/>");
        text.append("如果您没有进行上述操作，请忽略此邮件。");
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();

        // 发件配置并发送邮件
        try {
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage);
            //这里只是设置username 并没有设置host和password，因为host和password在springboot启动创建JavaMailSender实例的时候已经读取了
            mimeMessageHelper.setFrom(mailUserName,"售后服务管理系统");
            // 用户的邮箱地址
            mimeMessageHelper.setTo(toEmail);
            // 邮件的标题
            mimeMessage.setSubject("【售后服务管理系统】--"+page+"验证");
            // 上面所拼接的邮件内容
            mimeMessageHelper.setText(text.toString(), true);
            threadService.sendMail(mimeMessage);
        }  catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        return Result.success("验证码发送成功，请登录邮箱查看");
    
    }
}
